package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.HttpConnectionUtil
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

// 每天晚上定时清理企微标签数据-为后面全量同步做准备
public class autoDealKafkaThread implements CallBackInvoke {
    private static final Logger log = LoggerFactory.getLogger(autoDealKafkaThread.class);
    private static String Main_Guid = "";
    private static String Thread_Guid = "";

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String paramString) {

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        String content = "";
        long startTime = System.currentTimeMillis();
        String taskSQL = '''Select Thread_Guid, Content
                              From Elitethread
                             Where Type = 'autoDealKafkaThread'
                               And Status = '0'
                               Order by Expand Limit 1000''';
        List<Map<String, Object>> taskList = jt.queryForList(taskSQL);
        for (int k = 0; k < taskList.size(); k++) {
            Map taskListMap = (Map) taskList.get(k);
            Main_Guid = taskListMap.get("Thread_Guid").toString();
            Thread_Guid = taskListMap.get("Content").toString();
            content = Thread_Guid;
            log.debug("InitThread Content Info:" + content);

            startTime = System.currentTimeMillis();
            int runResult = 2;
            String Log_Guid = "";
            String inData = "";

            // 标记线程执行中避免执行时间较长其他线程也开始调用
            String logSQL = '''Update Elitethread
                                   Set Status = 1,
                                    Expand = Date_Format(current_timestamp(6), '%Y-%m-%d %H:%i:%s.%f')
                                 Where Thread_Guid = ?''';
            int logRes = jt.update(logSQL, Main_Guid);
            log.debug("标记线程执行中-记录执行DB结果：" + logRes);

            // 查询任务对应的Kafka、Topic配置信息
            String selectSQL = "select Log_Guid, Request from ws_interface_log where Type = 'apiDealKafkaMsg' And Name = '内部调用' And Remark = ?";

            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, content);
            if (selectExits.size() > 0) {

                Map selectExitsm = selectExits.get(0);
                Log_Guid = selectExitsm.get("Log_Guid");
                inData = selectExitsm.get("Request");
                int listSize = 0;
                try {
                    //解析Json
                    JSONObject inJson = null;
                    try {
                        try {
                            log.debug("使用SF Json解析(默认)");
                            inJson = JSONObject.fromObject(inData);
                        } catch (Exception e) {
                            log.warn("使用SF Json解析(默认)异常信息Exception:" + e.getMessage());
                            String inDataF = filterJson(inData);
                            log.debug("使用SF Json解析(特殊字符过滤后):" + inDataF);
                            inJson = JSONObject.fromObject(inDataF);
                        }
                    } catch (Exception e) {
                        try {
                            log.debug("使用SF Json解析(特殊字符过滤后)异常信息Exception:" + e.getMessage());
                            inJson = JSONObject.fromObject(com.alibaba.fastjson.JSONObject.parseObject(inData));
                        } catch (Exception e2) {
                            log.warn("使用fastjson Json解析(默认)异常信息Exception:" + e.getMessage());
                            String inDataF = filterJson(inData);
                            log.debug("使用fastjson Json解析(特殊字符过滤后):" + inDataF);
                            inJson = JSONObject.fromObject(com.alibaba.fastjson.JSONObject.parseObject(inDataF));
                        }
                    }

                    if (inJson.getInt("code") != 1) {
                        runResult = 3;
                    } else {

                        List<String> sync_user_dp_List = new ArrayList<>();
                        List<String> sync_tag_user_List = new ArrayList<>();
                        List<String> sync_external_user_status_List = new ArrayList<>();

                        JSONArray dataArr = inJson.getJSONArray("data");
                        listSize = dataArr.size();
                        String topic = "";
                        String offset = "";
                        JSONObject valueJson = new JSONObject();
                        for (int i = 0; i < listSize; i++) {
                            topic = "";
                            offset = "";
                            valueJson.clear();

                            try {
                                topic = dataArr.getJSONObject(i).getString("topic");
                                offset = dataArr.getJSONObject(i).getString("offset");
                                valueJson = dataArr.getJSONObject(i).getJSONObject("value");

                                String resultFlag = "-Succ";
                                String resultMSG = "";

                                // 全量同步
                                if (topic == "sync_dp") {
                                    resultMSG = doDealAllDpt(eliteBean, valueJson);

                                } else if (topic == "sync_user_dp") {
                                    sync_user_dp_List.add(valueJson.toString());

                                } else if (topic == "sync_tag") {
                                    resultMSG = doDealAllTag(eliteBean, valueJson);

                                } else if (topic == "sync_tag_user") {
                                    sync_tag_user_List.add(valueJson.toString());

                                } else if (topic == "sync_external_user_status") {
                                    sync_external_user_status_List.add(valueJson.toString());

                                } else if (topic == "customer_msg") {
                                    resultMSG = doDealCustomer_Msg(eliteBean, valueJson);

                                } else if (topic == "external_contact") {// 增量外部联系人
                                    resultMSG = doDealExternal_User(eliteBean, valueJson);

                                } else if (topic == "address_book_call_back") {
                                    resultMSG = doDeal_AddressBook(eliteBean, valueJson);

                                }

                            } catch (Exception e) {
                                log.debug("当前数据异常-:topic【" + topic + "】 offset【" + offset + "】 解析异常信息:" + e.getMessage());
                            }

                        }

                        if (sync_user_dp_List.size() > 0) {
                            batchDealAllStaff(eliteBean, sync_user_dp_List);
                        }
                        if (sync_tag_user_List.size() > 0) {
                            batchDealAllTagUser(eliteBean, sync_tag_user_List);
                        }
                        if (sync_external_user_status_List.size() > 0) {
                            batchDealAllExternal_User(eliteBean, sync_external_user_status_List);
                        }
                    }

                    // 移除ws_interface_log数据
                    eliteBean.update("Insert Into Ws_Interface_Log_His (Log_Guid, Name, Time, Type, Request, Response, Consume, Remark) Select Log_Guid, Name, Time, Type, Request, Response, Consume, Remark From Ws_Interface_Log Where Log_Guid = '" + Log_Guid + "'", "dataSource");
                    eliteBean.update("Delete from ws_interface_log where Log_Guid = '" + Log_Guid + "'", "dataSource");

                } catch (Exception e) {
                    log.error(content + "-异常信息", e);
                    runResult = 3;
                } finally {
                    LogToDB.toDB(eliteBean, "dataSource", "线程处理", "autoDealKafkaThread", inData.replaceAll("'", "''"), "Result:" + runResult.toString() + "-Size:" + listSize, (System.currentTimeMillis() - startTime).toString(), content);
                }
            } else {
                runResult = 3;
                log.debug("企微全量同步数据多线程异步处理-无请求数据!");
            }

            logSQL = '''Update Elitethread
                                   Set Status = ?, Expand = Date_Format(current_timestamp(6), '%Y-%m-%d %H:%i:%s.%f')
                                 Where Thread_Guid = ?''';
            logRes = jt.update(logSQL, runResult, Main_Guid);
            log.debug("标记线程执行End-记录执行DB结果：" + logRes);

            // 移除ws_interface_log数据
            eliteBean.update("Insert Into Elitethread_His (Thread_Guid, Createdate, Status, Content, Type, Expand) Select Thread_Guid, Createdate, Status, Content, Type, Expand From Elitethread Where Thread_Guid = '" + Main_Guid + "'", "dataSource");
            eliteBean.update("Delete from Elitethread where Thread_Guid = '" + Main_Guid + "'", "dataSource");
        }
    }

    // 全量同步-部门
    public static String doDealAllDpt(EliteBean eliteBean, JSONObject inJson) {

        String departmentId = GetJV(inJson, "departmentId");
        String name = GetJV(inJson, "name");
        String parentId = GetJV(inJson, "parentId");

        log.debug("部门ID:" + departmentId + " 部门名称:" + name);
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 查询任务对应的Kafka、Topic配置信息
        String selectSQL = "select rec_guid from kh_qw_sync_dp where departmentId = ? and del_flag = 0";

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, departmentId);
        if (selectExits.size() > 0) {

            Map selectExitsm = selectExits.get(0);
            String rec_guid = selectExitsm.get("rec_guid");
            String updateSQL = "Update Kh_Qw_Sync_Dp Set Sync_Time = Now(), Name = ?, Parentid = ? Where Rec_Guid = ?";
            jt.update(updateSQL, name, parentId, rec_guid);
            log.debug("当前部门信息已存在!更新部门信息表数据");

        } else {
            String updateSQL = "Insert Into Kh_Qw_Sync_Dp (Rec_Guid, Departmentid, Name, Parentid, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, Now(), 0)";
            jt.update(updateSQL, departmentId, name, parentId);
            log.debug("当前部门信息无结果!新增部门信息表数据");
        }

    }

    // 全量同步-部门员工
    public static String doDealAllStaff(EliteBean eliteBean, JSONObject inJson) {

        String userId = GetJV(inJson, "userId");
        String mobile = GetJV(inJson, "mobile");
        String name = GetJV(inJson, "name");
        String status = GetJV(inJson, "status");
        JSONArray userDepartment = inJson.getJSONArray("userDepartment");

        int updateNum = 0;
        int updatecNum = 0;

        log.debug("员工ID:" + userId + " 员工部门:" + userDepartment + " 员工手机:" + mobile);
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 查询任务对应的Kafka、Topic配置信息
        String selectSQL = "select rec_guid from kh_qw_sync_user where userId = ? and del_flag = 0";

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, userId);
        if (selectExits.size() > 0) {

            Map selectExitsm = selectExits.get(0);
            String rec_guid = selectExitsm.get("rec_guid");
            String updateSQL = "Update kh_qw_sync_user Set Sync_Time = Now(), mobile = ?, name = ?, userDepartment = ?, status = ? Where Rec_Guid = ?";
            updateNum = jt.update(updateSQL, mobile, name, userDepartment.toString(), status, rec_guid);
            updateSQL = "Update Customer Set Workstatus = ? Where Customer_Id = ?";
            updatecNum = jt.update(updateSQL, status, userId);

            log.debug("当前员工信息已存在!更新员工信息表数据,更新kh_qw_sync_user:" + updateNum + " 更新Customer:" + updatecNum);

        } else {
            String updateSQL = "Insert Into kh_qw_sync_user (Rec_Guid, userId, mobile, name, status, userDepartment, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, ?, Now(), 0)";
            updateNum = jt.update(updateSQL, userId, mobile, name, status, userDepartment.toString());
            updateSQL = "Update Customer Set Workstatus = ? Where Customer_Id = ?";
            updatecNum = jt.update(updateSQL, status, userId);
            log.debug("当前员工信息无结果!新增员工信息表数据,新增kh_qw_sync_user:" + updateNum + " 更新Customer:" + updatecNum);
        }

        // 将当前员工现有归属部门清除
        String update2SQL = "update kh_qw_sync_user_dp set del_flag = 1 where userId = ? and del_flag = 0";
        jt.update(update2SQL, userId);
        for (int i = 0; i < userDepartment.size(); i++) {
            String departmentId = userDepartment.getString(i);
            String intsertSQL = "Insert Into kh_qw_sync_user_dp (Rec_Guid, userId, departmentId, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, Now(), 0)";
            jt.update(intsertSQL, userId, departmentId);
            log.debug("新增员工信息表数据");

        }
    }

    // 全量同步-批量部门员工
    public static String batchDealAllStaff(EliteBean eliteBean, List<String> sync_user_dp_List) {

        int listSize = sync_user_dp_List.size();

        int loopNum = 0;
        List<String> batchDealSQL = new ArrayList<>();
        String[] SQLArray = new String[0];
        int[] SQLArrayRes = null;

        List<Object[]> paramListUid = new ArrayList<>();
        List<Object[]> paramListCus = new ArrayList<>();
        List<Object[]> paramList = new ArrayList<>();
        List<Object[]> paramListDP = new ArrayList<>();
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        for (int i = 0; i < listSize; i++) {

            JSONObject inJson = JSONObject.fromObject(sync_user_dp_List.get(i));

            // 解析单条数据
            String userId = GetJV(inJson, "userId");
            String mobile = GetJV(inJson, "mobile");
            String name = GetJV(inJson, "name");
            String status = GetJV(inJson, "status");
            JSONArray userDepartment = inJson.getJSONArray("userDepartment");

            // 批量处理当前员工部门关系
            for (int j = 0; j < userDepartment.size(); j++) {
                String departmentId = userDepartment.getString(j);
                String[] DPArr = new String[2];
                DPArr[0] = userId;
                DPArr[1] = departmentId;
                paramListDP.add(DPArr);
            }


            String[] UidArr = new String[1];
            UidArr[0] = userId;
            paramListUid.add(UidArr);

            String[] CusArr = new String[2];
            CusArr[0] = status;
            CusArr[1] = userId;
            paramListCus.add(CusArr);

            String[] paramArr = new String[5];
            paramArr[0] = userId;
            paramArr[1] = mobile;
            paramArr[2] = name;
            paramArr[3] = status;
            paramArr[4] = userDepartment;
            paramList.add(paramArr);

            loopNum++;

            // 如果当前批次员工已经到100提交一次DB
            if (loopNum >= 200) {

                log.debug("如果当前批次员工已经到" + loopNum + "提交一次DB");
                String batchInsert = "Delete From Kh_Qw_Sync_User Where Userid = ?";
                jt.batchUpdate(batchInsert, paramListUid);

                batchInsert = "Insert Into kh_qw_sync_user (Rec_Guid, userId, mobile, name, status, userDepartment, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, ?, Now(), 0)";
                jt.batchUpdate(batchInsert, paramList);

                batchInsert = "Update Customer Set Workstatus = ? Where Customer_Id = ?";
                jt.batchUpdate(batchInsert, paramListCus);

                batchInsert = "Delete From Kh_Qw_Sync_User_Dp Where Userid = ?";
                jt.batchUpdate(batchInsert, paramListUid);

                batchInsert = "Insert Into kh_qw_sync_user_dp (Rec_Guid, userId, departmentId, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, Now(), 0)";
                jt.batchUpdate(batchInsert, paramListDP);
                log.debug("如果当前批次员工已经到" + loopNum + "提交一次DB End");
                paramListUid.clear();
                paramListCus.clear();
                paramList.clear();
                paramListDP.clear();

                loopNum = 0;
            }

        }

        // 最后批次员工未达到100提交一次DB
        if (loopNum > 0) {
            log.debug("最后批次员工达到" + loopNum + "提交一次DB");
            String batchInsert = "Delete From Kh_Qw_Sync_User Where Userid = ?";
            jt.batchUpdate(batchInsert, paramListUid);

            batchInsert = "Insert Into kh_qw_sync_user (Rec_Guid, userId, mobile, name, status, userDepartment, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, ?, Now(), 0)";
            jt.batchUpdate(batchInsert, paramList);

            batchInsert = "Update Customer Set Workstatus = ? Where Customer_Id = ?";
            jt.batchUpdate(batchInsert, paramListCus);

            batchInsert = "Delete From Kh_Qw_Sync_User_Dp Where Userid = ?";
            jt.batchUpdate(batchInsert, paramListUid);

            batchInsert = "Insert Into kh_qw_sync_user_dp (Rec_Guid, userId, departmentId, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, Now(), 0)";
            jt.batchUpdate(batchInsert, paramListDP);
            log.debug("最后批次员工达到" + loopNum + "提交一次DB End");
        }
    }

    // 全量同步-标签字典
    public static String doDealAllTag(EliteBean eliteBean, JSONObject inJson) {

        String tagId = GetJV(inJson, "tagId");
        String tagName = GetJV(inJson, "tagName");

        if (!KHUtil.isNull(tagName)) {

            log.debug("TagID:" + tagId + " Tag名称:" + tagName);
            JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

            // 查询任务对应的Kafka、Topic配置信息
            String selectSQL = "select rec_guid from kh_qw_sync_tag where tagId = ? and del_flag = 0";

            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, tagId);
            if (selectExits.size() > 0) {

                Map selectExitsm = selectExits.get(0);
                String rec_guid = selectExitsm.get("rec_guid");
                String updateSQL = "Update kh_qw_sync_tag Set Sync_Time = Now(), tagName = ? Where Rec_Guid = ?";
                jt.update(updateSQL, tagName, rec_guid);
                log.debug("当前Tag信息已存在!更新Tag信息表数据");

            } else {
                String updateSQL = "Insert Into kh_qw_sync_tag (Rec_Guid, tagId, tagName, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, Now(), 0)";
                jt.update(updateSQL, tagId, tagName);
                log.debug("当前Tag信息无结果!新增Tag信息表数据");
            }
        }

    }

    // 全量同步-标签字典
    public static String batchDealAllTagUser(EliteBean eliteBean, List<String> sync_tag_user_List) {
        int listSize = sync_tag_user_List.size();

        int loopNum = 0;

        List<Object[]> paramListDel = new ArrayList<>();
        List<Object[]> paramListIns = new ArrayList<>();
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        for (int i = 0; i < listSize; i++) {

            JSONObject inJson = JSONObject.fromObject(sync_tag_user_List.get(i));

            String tagId = GetJV(inJson, "tagId");
            String mobile = GetJV(inJson, "mobile");
            String userId = GetJV(inJson, "userId");
            String status = GetJV(inJson, "status");

            String eventType = GetJV(inJson, "eventType");

            String del_flag = eventType == "del" ? "1" : "0";
            log.debug("TagID:" + tagId + " userId:" + userId + " eventType:" + eventType + " del_flag:" + del_flag);

            status = KHUtil.isNull(status) ? "1" : status;

            String[] CusArr = new String[2];
            CusArr[0] = tagId;
            CusArr[1] = userId;
            paramListDel.add(CusArr);

            String[] paramArr = new String[5];
            paramArr[0] = tagId;
            paramArr[1] = userId;
            paramArr[2] = mobile;
            paramArr[3] = status;
            paramArr[4] = del_flag;
            paramListIns.add(paramArr);

            loopNum++;

            // 如果当前批次已经到100提交一次DB
            if (loopNum >= 200) {

                log.debug("如果当前批次已经到" + loopNum + "提交一次DB");
                String batchInsert = "Delete From kh_qw_sync_taguser where tagId = ? and userId = ?";
                jt.batchUpdate(batchInsert, paramListDel);

                batchInsert = "Insert Into kh_qw_sync_taguser (Rec_Guid, tagId, userId, mobile, status, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, Now(), ?)";
                jt.batchUpdate(batchInsert, paramListIns);
                log.debug("如果当前批次已经到" + loopNum + "提交一次DB End");
                paramListDel.clear();
                paramListIns.clear();

                loopNum = 0;
            }
        }

        // 最后批次未达到100提交一次DB
        if (loopNum > 0) {
            log.debug("最后批次达到" + loopNum + "提交一次DB");
            String batchInsert = "Delete From kh_qw_sync_taguser where tagId = ? and userId = ?";
            jt.batchUpdate(batchInsert, paramListDel);

            batchInsert = "Insert Into kh_qw_sync_taguser (Rec_Guid, tagId, userId, mobile, status, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, Now(), ?)";
            jt.batchUpdate(batchInsert, paramListIns);
            log.debug("最后批次达到" + loopNum + "提交一次DB End");
        }

    }

    // 全量同步-员工标签
    public static String doDealAllTagUser(EliteBean eliteBean, JSONObject inJson) {

        String tagId = GetJV(inJson, "tagId");
        String mobile = GetJV(inJson, "mobile");
        String userId = GetJV(inJson, "userId");
        String status = GetJV(inJson, "status");

        String eventType = GetJV(inJson, "eventType");

        String del_flag = eventType == "del" ? "1" : "0";
        log.debug("TagID:" + tagId + " userId:" + userId + " eventType:" + eventType + " del_flag:" + del_flag);
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        status = KHUtil.isNull(status) ? "1" : status;

        // 查询任务对应的Kafka、Topic配置信息
        String selectSQL = "select rec_guid from kh_qw_sync_taguser where tagId = ? and userId = ? order by del_flag limit 1";

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, tagId, userId);
        if (selectExits.size() > 0) {

            Map selectExitsm = selectExits.get(0);
            String rec_guid = selectExitsm.get("rec_guid");
            String updateSQL = "Update kh_qw_sync_taguser Set Sync_Time = Now(), mobile = ?, status = ?, del_flag = ? Where Rec_Guid = ?";
            jt.update(updateSQL, mobile, status, del_flag, rec_guid);
            log.debug("当前TagUser信息已存在!更新TagUser信息表数据del_flag:" + del_flag);

        } else {
            String updateSQL = "Insert Into kh_qw_sync_taguser (Rec_Guid, tagId, userId, mobile, status, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, ?, Now(), ?)";
            jt.update(updateSQL, tagId, userId, mobile, status, del_flag);
            log.debug("当前TagUser信息无结果!新增TagUser信息表数据");
        }

    }

    // 全量同步-外部联系人（微信好友）
    public static String doDealAllExternal_User(EliteBean eliteBean, JSONObject inJson) {

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        /*
        {
            "unionid": "oCv2b6QyA22g39hH_-9w8BZuRlLs",
            "gender": "1",
            "mobile": "17600665712",
            "description": "华盛号：111",
            "remark": "111-张三",
            "avatar": "http://wx.qlogo.cn/mmhead/WBfKeyQ80wKjibkT9GaVQovAKFhNIFG0JV2eXH9zBv4U/0",
            "type": "1",
            "followUserId": "Lu",
            "externalUserId": "wmaC1yDgAA7AQH83eqAtBUqFnPRuiRWQ",
            "name": "路",
            "corpName": "",
            "corpFullName": "",
            "externalProfile": ""
        }
        */

        String unionid = GetJV(inJson, "unionid");
        String gender = GetJV(inJson, "gender");
        String mobile = GetJV(inJson, "mobile");
        String description = GetJV(inJson, "description");
        String remark = GetJV(inJson, "remark");
        String avatar = GetJV(inJson, "avatar");
        String type = GetJV(inJson, "type");
        String followUserId = GetJV(inJson, "followUserId");
        String externalUserId = GetJV(inJson, "externalUserId");
        String name = GetJV(inJson, "name");
        String corpName = GetJV(inJson, "corpName");
        String corpFullName = GetJV(inJson, "corpFullName");
        String externalProfile = GetJV(inJson, "externalProfile");
        String createTime = GetJV(inJson, "createTime");

        log.debug("全量同步-外部联系人（微信好友）externalUserId:" + externalUserId + " mobile:" + mobile);

        // 查询任务对应的Kafka、Topic配置信息
        String selectSQL = "select rec_guid from kh_qw_sync_external_contact where externalUserId = ? and followUserId = ? and del_flag = 0";

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, externalUserId, followUserId);
        if (selectExits.size() > 0) {

            Map selectExitsm = selectExits.get(0);
            String rec_guid = selectExitsm.get("rec_guid");
            String updateSQL = "UPDATE kh_qw_sync_external_contact SET externalUserId = ?, followUserId = ?, unionid = ?, name = ?, type = ?, avatar = ?, gender = ?, description = ?, remark = ?, mobile = ?, staffId = ?, createTime = ?, sync_time = now(), del_flag = 0 WHERE rec_guid = ?";
            jt.update(updateSQL, externalUserId, followUserId, unionid, name, type, avatar, gender, description, remark, mobile, "SELITE", createTime, rec_guid);
            log.debug("全量同步-外部联系人（微信好友）当前外部联系人添加信息已存在!更新外部联系人添加信息表数据");

        } else {
            String updateSQL = "INSERT INTO kh_qw_sync_external_contact (rec_guid, externalUserId, followUserId, unionid, name, type, avatar, gender, description, remark, mobile, staffId, sync_time, del_flag, createTime) VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SELITE', NOW(), 0, ?)";
            jt.update(updateSQL, externalUserId, followUserId, unionid, name, type, avatar, gender, description, remark, mobile, createTime);
            log.debug("全量同步-外部联系人（微信好友）当前外部联系人添加信息无结果!新增外部联系人添加信息表数据");
        }

        // 1-处理外部联系人与集中作业平台客户之间的关系-通过客户备注信息拆分出资金账号
        String updateCustID = '''Update Kh_Qw_Sync_External_Contact
                                   Set Userid = Case
                                                  When Length(Extractnumber(Remark)) >= 9 Then
                                                   Extractnumber(Remark)
                                                  Else
                                                   Null
                                                End
                                 Where externalUserId = ?''';
        jt.update(updateCustID, externalUserId);
        log.debug("1-处理外部联系人与集中作业平台客户之间的关系-通过客户备注信息拆分出资金账号");

        // 2-处理外部联系人与集中作业平台客户之间的关系-通过手机号与customer关联取资金账号
        updateCustID = '''Update Kh_Qw_Sync_External_Contact R1, Customer R2
                           Set R1.Userid = R2.Customer_Id
                         Where R1.Mobile = R2.Mobile
                           And R1.Externaluserid = ?
                           And R2.Mobile = ?
                           And R2.Customer_Id Is Not Null
                           And R2.Customer_Id != ''
                           And (R1.Userid Is Null Or R1.Userid != '')''';
        jt.update(updateCustID, externalUserId, mobile);
        log.debug("2-处理外部联系人与集中作业平台客户之间的关系-通过手机号与customer关联取资金账号");

    }

    // 全量同步-外部联系人（微信好友）
    public static String batchDealAllExternal_User(EliteBean eliteBean, List<String> sync_external_user_status_List) {
        int listSize = sync_external_user_status_List.size();

        int loopNum = 0;

        List<Object[]> paramListDel = new ArrayList<>();
        List<Object[]> paramListIns = new ArrayList<>();
        List<Object[]> paramListCus = new ArrayList<>();
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        for (int i = 0; i < listSize; i++) {

            JSONObject inJson = JSONObject.fromObject(sync_external_user_status_List.get(i));

            String unionid = GetJV(inJson, "unionid");
            String gender = GetJV(inJson, "gender");
            String mobile = GetJV(inJson, "mobile");
            String description = GetJV(inJson, "description");
            String remark = GetJV(inJson, "remark");
            String avatar = GetJV(inJson, "avatar");
            String type = GetJV(inJson, "type");
            String followUserId = GetJV(inJson, "followUserId");
            String externalUserId = GetJV(inJson, "externalUserId");
            String name = GetJV(inJson, "name");
            String createTime = GetJV(inJson, "createTime");
            log.debug("全量同步-外部联系人（微信好友）externalUserId:" + externalUserId + " mobile:" + mobile + " inJson:" + inJson);

            String[] delArr = new String[2];
            delArr[0] = externalUserId;
            delArr[1] = followUserId;
            paramListDel.add(delArr);

            String[] insArr = new String[13];
            insArr[0] = externalUserId;
            insArr[1] = followUserId;
            insArr[2] = unionid;
            insArr[3] = name;
            insArr[4] = type;
            insArr[5] = avatar;
            insArr[6] = gender;
            insArr[7] = description;
            insArr[8] = remark;
            insArr[9] = mobile;
            insArr[10] = createTime;
            insArr[11] = remark;
            insArr[12] = remark;
            paramListIns.add(insArr);

            String[] cusArr = new String[2];
            cusArr[0] = externalUserId;
            cusArr[1] = mobile;
            paramListCus.add(cusArr);

            loopNum++;

            // 如果当前批次已经到100提交一次DB
            if (loopNum >= 200) {

                log.debug("如果当前批次已经到" + loopNum + "提交一次DB");
                String batchInsert = '''Delete From Kh_Qw_Sync_External_Contact Where Externaluserid = ? And Followuserid = ?''';
                jt.batchUpdate(batchInsert, paramListDel);

                batchInsert = "Insert Into Kh_Qw_Sync_External_Contact (Rec_Guid, Externaluserid, Followuserid, Unionid, Name, Type, Avatar, Gender, Description, Remark, Mobile, Staffid, Sync_Time, Del_Flag, Createtime, Userid) Values (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SELITE', Now(), 0, ?, Case When Length(Extractnumber(?)) >= 9 Then Extractnumber(?) Else Null End)";
                jt.batchUpdate(batchInsert, paramListIns);

                batchInsert = '''Update Kh_Qw_Sync_External_Contact R1, Customer R2
                           Set R1.Userid = R2.Customer_Id
                         Where R1.Mobile = R2.Mobile
                           And R1.Externaluserid = ?
                           And R2.Mobile = ?
                           And R2.Customer_Id Is Not Null
                           And R2.Customer_Id != ''
                           And (R1.Userid Is Null Or R1.Userid != '')''';
                jt.batchUpdate(batchInsert, paramListCus);
                log.debug("如果当前批次已经到" + loopNum + "提交一次DB End");
                paramListDel.clear();
                paramListIns.clear();
                paramListCus.clear();

                loopNum = 0;
            }
        }

        // 最后批次未达到100提交一次DB
        if (loopNum > 0) {
            log.debug("最后批次达到" + loopNum + "提交一次DB");
            String batchInsert = '''Delete From Kh_Qw_Sync_External_Contact Where Externaluserid = ? And Followuserid = ?''';
            jt.batchUpdate(batchInsert, paramListDel);

            batchInsert = "Insert Into Kh_Qw_Sync_External_Contact (Rec_Guid, Externaluserid, Followuserid, Unionid, Name, Type, Avatar, Gender, Description, Remark, Mobile, Staffid, Sync_Time, Del_Flag, Createtime, Userid) Values (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SELITE', Now(), 0, ?, Case When Length(Extractnumber(?)) >= 9 Then Extractnumber(?) Else Null End)";
            jt.batchUpdate(batchInsert, paramListIns);

            batchInsert = '''Update Kh_Qw_Sync_External_Contact R1, Customer R2
                           Set R1.Userid = R2.Customer_Id
                         Where R1.Mobile = R2.Mobile
                           And R1.Externaluserid = ?
                           And R2.Mobile = ?
                           And R2.Customer_Id Is Not Null
                           And R2.Customer_Id != ''
                           And (R1.Userid Is Null Or R1.Userid != '')''';
            jt.batchUpdate(batchInsert, paramListCus);
            log.debug("最后批次达到" + loopNum + "提交一次DB End");
        }

    }

    // 增量同步-添加外部联系人（微信好友）
    public static String doDealExternal_User(EliteBean eliteBean, JSONObject inJson) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        // add_external_contact 添加
        // edit_external_contact 更新
        // del_external_contact 删除
        /*
            {
                "unionid":"oCv2b6QyA22g39hH_-9w8BZuRlLs",
                "gender":"1",
                "changeType":"add_external_contact",
                "mobile":"17600665712",
                "description":"华盛号：111",
                "remark":"111-张三",
                "avatar":"http://wx.qlogo.cn/mmhead/WBfKeyQ80wKjibkT9GaVQovAKFhNIFG0JV2eXH9zBv4U/0",
                "type":"1",
                "followUserId":"Lu",
                "externalUserId":"wmaC1yDgAA7AQH83eqAtBUqFnPRuiRWQ",
                "name":"路",
                "externalProfile":""
            }
        */

        String externalUserId = inJson.getString("externalUserId");
        String changeType = inJson.getString("changeType");
        log.debug("增量同步-外部联系人（微信好友）externalUserId:" + externalUserId + " changeType:" + changeType);

        if (changeType == "add_external_contact" || changeType == "edit_external_contact") {
            doDealAllExternal_User(eliteBean, inJson);

        } else if (changeType == "del_external_contact") {

            // 查询任务对应的Kafka、Topic配置信息
            String selectSQL = "select rec_guid from kh_qw_sync_external_contact where externalUserId = ? and del_flag = 0 limit 1";

            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, externalUserId);
            if (selectExits.size() > 0) {
                Map selectExitsm = selectExits.get(0);
                String rec_guid = selectExitsm.get("rec_guid");
                String updateSQL = "Update kh_qw_sync_external_contact Set Sync_Time = Now(), Del_Flag = 1 Where Rec_Guid = ?";
                jt.update(updateSQL, rec_guid);
                log.debug("增量同步-外部联系人（微信好友）当前外部联系人添加信息已存在!删除外部联系人添加信息表数据");

            } else {
                log.debug("增量同步-外部联系人（微信好友）当前外部联系人添加信息无结果!无需处理");
            }

        }

    }

    // 增量同步-企业通讯录-分发控制
    public static String doDeal_AddressBook(EliteBean eliteBean, JSONObject inJson) {

        String changeType = inJson.getString("changeType");
        // 部门信息（create_party；delete_party；update_party）
        // 标签变更（update_tag）
        // 成员变更（create_user；update_user；delete_user）
        if (changeType == "create_party" || changeType == "update_party" || changeType == "delete_party") {
            return doDeal_AddressBook_Party(eliteBean, inJson);
        } else if (changeType == "update_tag") {
            return doDeal_AddressBook_Tag(eliteBean, inJson);
        } else if (changeType == "create_user" || changeType == "update_user" || changeType == "delete_user") {
            return doDeal_AddressBook_User(eliteBean, inJson);
        } else {
            return "未知的增量变更类型-" + changeType;
        }
    }

    // 增量同步-部门信息变更
    public static String doDeal_AddressBook_Party(EliteBean eliteBean, JSONObject inJson) {

        // 部门信息（create_party；delete_party；update_party）
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String departmentId = GetJV(inJson, "departmentId");
        String name = GetJV(inJson, "name");
        String parentId = GetJV(inJson, "parentId");
        String changeType = GetJV(inJson, "changeType");
        log.debug("增量同步-部门信息变更changeType:" + changeType + "departmentId:" + departmentId + " name" + name + " parentId" + parentId);

        // 查询任务对应的Kafka、Topic配置信息
        String selectSQL = "select rec_guid from kh_qw_sync_dp where departmentId = ? and del_flag = 0";

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, departmentId);

        if (changeType == "create_party" || changeType == "update_party") {
            if (selectExits.size() > 0) {

                Map selectExitsm = selectExits.get(0);
                String rec_guid = selectExitsm.get("rec_guid");
                if (changeType == "create_party") {
                    String updateSQL = "Update Kh_Qw_Sync_Dp Set Sync_Time = Now(), Name = ?, Parentid = ? Where Rec_Guid = ?";
                    jt.update(updateSQL, name, parentId, rec_guid);

                } else {
                    // changeType为update_party时没有parentId
                    String updateSQL = "Update Kh_Qw_Sync_Dp Set Sync_Time = Now(), Name = ? Where Rec_Guid = ?";
                    jt.update(updateSQL, name, rec_guid);

                }
                log.debug("当前部门信息已存在!更新部门信息表数据");

            } else {
                String updateSQL = "Insert Into Kh_Qw_Sync_Dp (Rec_Guid, Departmentid, Name, Parentid, Sync_Time, Del_Flag) Values (Uuid(), ?, ?, ?, Now(), 0)";
                jt.update(updateSQL, departmentId, name, parentId);
                log.debug("当前部门信息无结果!新增部门信息表数据");
            }

        } else if (changeType == "delete_party") {
            if (selectExits.size() > 0) {

                Map selectExitsm = selectExits.get(0);
                String updateSQL = "Update Kh_Qw_Sync_Dp Set Sync_Time = Now(), Del_Flag = 1 Where Rec_Guid = ?";
                jt.update(updateSQL, selectExitsm.get("rec_guid"));
                log.debug("当前部门信息已存在!删除标识部门信息表数据");

            } else {

                log.debug("当前部门信息无结果!忽略处理");
            }

        }

    }

    // 增量同步-标签变更
    public static String doDeal_AddressBook_Tag(EliteBean eliteBean, JSONObject inJson) {

        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        /*
         {
            "tagId": "10",
            "changeType": "update_tag",
            "delUserItems": "LingYu,dnd,ChenXu",
            "addUserItems": "LingYu,dnd,ChenXu",
            "tagName": "测试11111111111"
         }
        */

        String tagId = GetJV(inJson, "tagId");
        String tagName = GetJV(inJson, "tagName");
        String delUserItems = GetJV(inJson, "delUserItems");
        String addUserItems = GetJV(inJson, "addUserItems");
        String changeType = GetJV(inJson, "changeType");

        log.debug("增量同步-标签变更tagId:" + tagId + " tagName" + tagName + " delUserItems" + delUserItems + " addUserItems" + addUserItems);

        if (changeType == "update_tag") {

            // 先将消息送给标签处理保证标签字典入库
            doDealAllTag(eliteBean, inJson);
            log.debug("处理给标签处理保证标签字典入库:" + inJson.toString());

            // 先处理需要删除的标签关系
            String[] delUserArr = KHUtil.isNull(delUserItems) ? new String[0] : delUserItems.split(",");
            JSONObject userListJson = new JSONObject();
            for (int i = 0; i < delUserArr.length; i++) {

                userListJson.put("tagId", tagId);
                userListJson.put("mobile", "/");
                userListJson.put("userId", delUserArr[i]);
                userListJson.put("status", "1");
                userListJson.put("eventType", "del");
                doDealAllTagUser(eliteBean, userListJson);

            }
            log.debug("处理需要删除的标签关系完成:" + delUserArr.size());

            // 再处理标签对应需要的新增
            String[] addUserArr = KHUtil.isNull(addUserItems) ? new String[0] : addUserItems.split(",");
            for (int i = 0; i < addUserArr.length; i++) {

                userListJson.put("tagId", tagId);
                userListJson.put("mobile", "/");
                userListJson.put("userId", addUserArr[i]);
                userListJson.put("status", "1");
                userListJson.put("eventType", "add");
                doDealAllTagUser(eliteBean, userListJson);

            }
            log.debug("处理标签对应需要的新增完成:" + addUserArr.size());
        }

    }

    // 增量同步-成员变更
    public static String doDeal_AddressBook_User(EliteBean eliteBean, JSONObject inJson) {
        // 成员变更（create_user；update_user；delete_user）
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        String userId = GetJV(inJson, "userId");
        String mobile = GetJV(inJson, "mobile");
        String status = GetJV(inJson, "status");
        String departmentId = GetJV(inJson, "department");
        String changeType = GetJV(inJson, "changeType");
        log.debug("增量同步-成员变更department:" + departmentId + " userId" + userId + " mobile" + mobile + " status" + status + " changeType" + changeType);

        if (changeType == "create_user" || changeType == "update_user") {
            JSONObject changeUser = new JSONObject();
            JSONArray userDepartment = new JSONArray();

            changeUser.put("userId", userId);
            changeUser.put("mobile", mobile);
            changeUser.put("status", status);
            userDepartment.add(departmentId);
            changeUser.put("userDepartment", userDepartment);

            doDealAllStaff(eliteBean, changeUser);

        } else if (changeType == "delete_user") {

            // 查询任务对应的Kafka、Topic配置信息
            String selectSQL = "select rec_guid from kh_qw_sync_user where userId = ? and del_flag = 0";

            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, userId);
            if (selectExits.size() > 0) {

                Map selectExitsm = selectExits.get(0);
                String rec_guid = selectExitsm.get("rec_guid");
                String updateSQL = "Update kh_qw_sync_user Set Sync_Time = Now(), del_flag = 1 Where Rec_Guid = ?";
                jt.update(updateSQL, rec_guid);
                updateSQL = "Update Customer Set Workstatus = Null Where Customer_Id = ?";
                jt.update(updateSQL, userId);

                log.debug("当前员工信息已存在!标识删除员工信息表数据");

            } else {
                log.debug("当前员工信息无结果!忽略数据处理");
            }

        }

    }

    // 全量同步-客户聊天信息
    public static String doDealCustomer_Msg(EliteBean eliteBean, JSONObject inJson) {

        String MsgType = GetJV(inJson, "MsgType");
        String AgentID = GetJV(inJson, "AgentID");
        String MsgId = GetJV(inJson, "MsgId");
        String CreateTime = GetJV(inJson, "CreateTime");
        String ToUserName = GetJV(inJson, "ToUserName");
        String FromUserName = GetJV(inJson, "FromUserName");
        String Content = "";
        String MediaId = "";
        String PicUrl = "";
        String Format = "";
        String ThumbMediaId = ""; //

        String Location_X = ""; //地理位置纬度
        String Location_Y = ""; //地理位置经度
        String Scale = ""; //地图缩放大小
        String Label = ""; //地理位置信息
        String AppType = ""; //app类型，在企业微信固定返回wxwork，在微信不返回该字段

        String Title = ""; //标题
        String Description = ""; //描述
        String Url = ""; //链接跳转的url

        if (MsgType == "text") {
            Content = GetJV(inJson, "Content");

        } else if (MsgType == "image") {
            MediaId = GetJV(inJson, "MediaId");
            PicUrl = GetJV(inJson, "PicUrl");
            try {
                String saveFile = getQWFile(eliteBean, MediaId);
                if (KHUtil.isNull(saveFile)) {
                    Content = PicUrl;
                } else {
                    Content = KHDBConfig.getAPIURL(eliteBean, "NGS-OuterDomain") + "/fs/get?file=" + uploadNGS(eliteBean, saveFile);
                    Util.deleteFile(saveFile);
                }
            } catch (Exception e) {
                log.warn("下载消息记录中的图片到本地异常：", e);
                Content = PicUrl;
            }

        } else if (MsgType == "voice") {
            MediaId = GetJV(inJson, "MediaId");
            Format = GetJV(inJson, "Format");
            try {
                String saveFile = getQWFile(eliteBean, MediaId);
                if (KHUtil.isNull(saveFile)) {
                    Content = "[不支持的消息格式:语音]";
                } else {
                    Content = KHDBConfig.getAPIURL(eliteBean, "NGS-OuterDomain") + "/fs/get?file=" + uploadNGS(eliteBean, saveFile);
                    Util.deleteFile(saveFile);
                }
            } catch (Exception e) {
                log.warn("下载消息记录中的图片到本地异常：", e);
                Content = "[不支持的消息格式:语音]";
            }

        } else if (MsgType == "video") {
            MediaId = GetJV(inJson, "MediaId");
            ThumbMediaId = GetJV(inJson, "ThumbMediaId");
            try {
                String saveFile = getQWFile(eliteBean, MediaId);
                if (KHUtil.isNull(saveFile)) {
                    Content = "[不支持的消息格式:视频]";
                } else {
                    Content = KHDBConfig.getAPIURL(eliteBean, "NGS-OuterDomain") + "/fs/get?file=" + uploadNGS(eliteBean, saveFile);
                    Util.deleteFile(saveFile);
                }
            } catch (Exception e) {
                log.warn("下载消息记录中的图片到本地异常：", e);
                Content = "[不支持的消息格式:视频]";
            }

        } else if (MsgType == "location") {
            Location_X = GetJV(inJson, "Location_X");
            Location_Y = GetJV(inJson, "Location_Y");
            Scale = GetJV(inJson, "Scale");
            Label = GetJV(inJson, "Label");
            AppType = GetJV(inJson, "AppType");

            Content = Label;

        } else if (MsgType == "link") {
            Title = GetJV(inJson, "Title");
            Description = GetJV(inJson, "Description");
            Url = GetJV(inJson, "Url");
            PicUrl = GetJV(inJson, "PicUrl");

            Content = Url;

        }

        log.debug("MsgType:" + MsgType + " AgentID:" + AgentID + " MsgId:" + MsgId + " CreateTime:" + CreateTime + " ToUserName:" + ToUserName + " FromUserName:" + FromUserName);
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 查询任务对应的Kafka、Topic配置信息
        String selectSQL = "select Rec_Guid from kh_qw_chat_msg where MsgId = ? and AgentID = ?";

        List<Map<String, Object>> selectExits = jt.queryForList(selectSQL, MsgId, AgentID);
        if (selectExits.size() > 0) {
            log.debug("当前Msg信息已存在!更新Msg信息表数据");

        } else {
            String updateSQL = "Insert Into Kh_Qw_Chat_Msg (Rec_Guid, Msgid, Agentid, Createtime, Fromusername, Tousername, Msgtype, Content, Mediaid, Picurl, Sync_Time, Format, ThumbMediaId, Location_X, Location_Y, Scale, Label, AppType, Title, Description, Url) Values (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, Now(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            jt.update(updateSQL, MsgId, AgentID, CreateTime, FromUserName, ToUserName, MsgType, Content, MediaId, PicUrl, Format, ThumbMediaId, Location_X, Location_Y, Scale, Label, AppType, Title, Description, Url);
            log.debug("当前Msg信息无结果!新增Msg信息表数据");
        }

    }

    // 解析Json值(此方法增加需要解析的key不存在保护)
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }

    // 上传文件到NGS
    public static String uploadNGS(EliteBean eliteBean, String srcFileName) {

        String ngsFSToken = Util.getAuthToken(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-authUrl"), "elite.ngs", "Letmein_0308");
        log.debug("获取NGS上次Token：" + ngsFSToken);

        File tempFile = new File(srcFileName.trim());
        String fileName = tempFile.getName();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date = sdf.format(new Date());

        String uploadResult = Util.uploadFile(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-upload_url"), srcFileName, "/qwmsg/" + date + "/", getNameWithoutSuffix(fileName), "", ngsFSToken);
        log.debug("文件上传NGS结果：" + uploadResult);

        JSONObject resultJson = JSONObject.fromObject(uploadResult);

        String code = resultJson.getString("code");
        if (code == "1") {
            return resultJson.getString("value");
        } else {
            return null;
        }
    }

    public static String getNameWithoutSuffix(String filename) {
        try {
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf(".");
                if ((dot > -1) && (dot < filename.length()))
                    return filename.substring(0, dot);
            }
        } catch (Exception e) {
            log.error("Exception", e);
        }
        return filename;
    }

    public static String getQWFile(EliteBean eliteBean, String MediaId) {

        String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "EliteInner-API");
        JSONObject apiTokenJson = JSONObject.fromObject(Util.doHttpGet(DOMAIN + "/apiGetToken?appid=WXG", "UTF-8", 5000, 0));
        log.debug("企微TOKEN信息：" + apiTokenJson.toString());
        String access_token = apiTokenJson.getJSONObject("data").getString("access_token");

        String dFileURL = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token + "&media_id=" + MediaId;
        log.debug("企微下载信息：" + dFileURL);
        String saveFile = HttpConnectionUtil.downloadFile(dFileURL, KHDBConfig.getParam(eliteBean, "APITMF"));
        log.debug("企微下载文件：" + saveFile);

        return saveFile;
    }

    /**
     * JSON字符串特殊字符处理，比如：“\A1;1300”
     *
     * @param inData
     * @return String
     */
    public static String filterJson(String inData) {
        List<String> filterList = new ArrayList<>();
        filterList.add("\\\\");
        filterList.add("¥");
        filterList.add("@");
        filterList.add("\b");
        filterList.add("\f");
        filterList.add("\n");
        filterList.add("\n");
        filterList.add("\t");

        for (int i = 0; i < filterList.size(); i++) {
            inData = inData.replaceAll(filterList.get(i), "");
        }
        inData = inData.replaceAll("'", "''");
        inData = toJsonString(inData);
        // inData = toJson2String(inData);
        return inData;
    }

    // 处理json字符串中value多余的双引号， 将多余的双引号替换为中文双引号
    private static String toJsonString(String s) {
        char[] tempArr = s.toCharArray();
        int tempLength = tempArr.length;
        for (int i = 0; i < tempLength; i++) {
            if (tempArr[i] == ':' && tempArr[i + 1] == '"') {
                for (int j = i + 2; j < tempLength; j++) {
                    if (tempArr[j] == '"') {
                        if (tempArr[j + 1] != ',' && tempArr[j + 1] != '}') {
                            tempArr[j] = '”'; // 将value中的 双引号替换为中文双引号
                        } else if (tempArr[j + 1] == ',' || tempArr[j + 1] == '}') {
                            break;
                        }
                    }
                }
            }
        }
        return new String(tempArr);
    }

    // 处理json字符串中value多余的双引号， 将多余的双引号替换为中文双引号
    private static String toJson2String(String s) {
        char[] tempArr = s.toCharArray();
        int tempLength = tempArr.length;
        for (int i = 0; i < tempLength; i++) {
            if (tempArr[i] == ':' && tempArr[i + 1] == '"') {
                for (int j = i + 2; j < tempLength; j++) {
                    if (tempArr[j] == ':') {
                        if (tempArr[j + 1] != ',' && tempArr[j + 1] != '}') {
                            tempArr[j] = ' '; // 将value中的 双引号替换为中文双引号
                        } else if (tempArr[j + 1] == ',' || tempArr[j + 1] == '}') {
                            break;
                        }
                    }
                }
            }
        }
        return new String(tempArr);
    }
}